package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        // 1. 开启分页功能
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        // 2. 执行分页查询
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        // 3. 封装分页结果
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveDishWithFlavor(DishDTO dishDTO) {
        // 1. 新增菜品，添加一条数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);

        // 2. 新增菜品口味，添加N条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            // 2.1. 设置菜品id
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            // 2.2. 批量插入口
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        // 1. 创建 DishVo 对象
        DishVO dishVO = new DishVO();

        // 2. 根据id查询菜品
        Dish dish = dishMapper.selectById(id);

        // 3. 根据菜品id查询菜品口味
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);

        // 4. 封装，将菜品和菜品口味组合
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);

        // 5. 返回
        return dishVO;
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteDishWithFlavor(List<Long> ids) {
        // 1. 判断菜品是否在起售
        for (Long id : ids) {
            Integer status = dishMapper.selectById(id).getStatus();
            if (status == StatusConstant.ENABLE) {
                // 1.1. 如果菜品在起售，抛出业务异常
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        // 2. 判断菜品是否关联了套餐
        for (Long id : ids) {
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishId(id);
            if (setmealIds != null && setmealIds.size() > 0) {
                // 2.2. 如果菜品关联了套餐，抛出业务异常
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }
        // 3. 删除菜品
        dishMapper.deleteBatchByIds(ids);

        // 4. 删除菜品口味
        dishFlavorMapper.deleteBatchByDishIds(ids);

    }

    /**
     * 菜品起售、停售
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStopDish(Integer status, Long id) {
        // 1. 构建 Dish 实体对象
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();

        // 2. 更新菜品状态
        dishMapper.update(dish);
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateDishWithFlavor(DishDTO dishDTO) {
        // 1. 构造 Dish 实体对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        // 2. 删除旧的菜品口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        // 3. 新增菜品口味，添加N条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            // 3.1. 设置菜品id
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            // 3.2. 批量插入口
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> listByCategoryId(Long categoryId) {
        // 1. 根据分类id查询菜品
        List<Dish> dishList = dishMapper.listDishByCategoryId(categoryId);

        // 2. 构造 DishVO 列表
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            // 2.1. 构造 DishVO 对象
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);
            // 2.2. 添加列表
            dishVOList.add(dishVO);
        }

        // 3. 返回数据
        return dishVOList;
    }

    /**
     * 根据条件查询菜品
     *
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        // 1. 根据分类id查询菜品
        List<Dish> dishList = dishMapper.listDishByCategoryId(dish.getCategoryId());

        // 2. 构造 DishVO 列表
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            // 2.1. 根据菜品id查询菜品口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());
            // 2.2. 构造 DishVO 对象
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);
            // 2.3. 将菜品口味添加到dishVO中
            dishVO.setFlavors(flavors);
            // 2.4. 添加列表
            dishVOList.add(dishVO);
        }

        // 3. 返回数据
        return dishVOList;
    }

}
